package com.cmsz.upay;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hive.serde2.Deserializer;
import org.apache.hadoop.hive.serde2.SerDeException;
import org.apache.hadoop.hive.serde2.SerDeStats;
import org.apache.hadoop.hive.serde2.objectinspector.ObjectInspector;
import org.apache.hadoop.hive.serde2.objectinspector.ObjectInspectorFactory;
import org.apache.hadoop.io.Writable;

import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import java.util.StringTokenizer;

/**
 * Created by le on 2017/12/18.
 */
public class BusinessExtractHive implements Deserializer {

    private List<String> structFieldNames = new ArrayList<String>();
    private List<ObjectInspector> structFieldObjectInspectors = new ArrayList<ObjectInspector>();

    public void initialize(Configuration configuration, Properties properties) throws SerDeException {
        structFieldNames.add("id");
        structFieldObjectInspectors.add(ObjectInspectorFactory
                .getReflectionObjectInspector(Integer.TYPE,
                        ObjectInspectorFactory.ObjectInspectorOptions.JAVA));
        structFieldNames.add("name");
        structFieldObjectInspectors.add(ObjectInspectorFactory
                .getReflectionObjectInspector(String.class,
                        ObjectInspectorFactory.ObjectInspectorOptions.JAVA));
    }

    public Object deserialize(Writable text) throws SerDeException {
        List<Object> result = new ArrayList<Object>();
        StringTokenizer tokenizer = new StringTokenizer(text.toString());
        int index = 0;

        while (tokenizer.hasMoreTokens()) {
            if (index == 0) {
                result.add(Integer.valueOf(tokenizer.nextToken()).intValue());
            } else {
                result.add(tokenizer.nextToken());
            }
            index++;
        }

        return result;
    }

    public ObjectInspector getObjectInspector() throws SerDeException {
        return ObjectInspectorFactory.getStandardStructObjectInspector(
                structFieldNames, structFieldObjectInspectors);
    }

    public SerDeStats getSerDeStats() {
        return null;
    }
}
